/** EasyWeb spa v3.1.8 date:2020-05-04 License By http://easyweb.vip */
layui.define(["layer", "element", "setter", "layRouter", "admin"], function (exports) {
    var jquery = layui.jquery;
    var layer = layui.layer;
    var element = layui.element;
    var setter = layui.setter;
    var layRouter = layui.layRouter;
    var admin = layui.admin;
    var ELEM_HEADER = ".layui-layout-admin>.layui-header";
    var ELEM_SCROLL = ".layui-layout-admin>.layui-side>.layui-side-scroll";
    var ELEM_BODY = ".layui-layout-admin>.layui-body";
    var ELEM_TAB = ELEM_BODY + ">.layui-tab";
    var ELEM_BODY_HEADER = ELEM_BODY + ">.layui-body-header";
    var ELEM_PAGETABS = "admin-pagetabs";
    var ELEM_NAV = "admin-side-nav";
    var o = false;
    var index = {mTabList: []};


    /**
     * 批量注册路由
     * @param menus 路由数组
     [{
        "name": "菜单名称",// 菜单名称
        "url": "", // 菜单路径
        "iframe": "", //
        "icon": "", // 菜单图标
        "show": true, //
        "subMenus": [] // 子菜单
     }]
     * @param callback 格式化函数，对菜单项处理的回调函数，可以处理后端返回的数据
     */
    index.regRouter = function (menus, callback) {
        jquery.each(menus, function (index1, element) {
            if (callback) {
                element = callback(element) // 回调函数对路由项进行处理
            }
            if (element.url && element.url.indexOf("#") === 0) { // 路径前面必须带#
                layRouter.reg(element.url, function (route) {
                    index.changeView(jquery.extend(route, {name: element.name, iframe: element.iframe}))
                });
            }
            if (element.subMenus) { // 递归调用
                index.regRouter(element.subMenus, callback)
            }
        })
    };

    index.changeView = function (router) {
        var routerPath = index.getHashPath(router); // 获取路由路径
        var t = ELEM_BODY + ">div[lay-id]";

        if (setter.pageTabs) { // 开启多标签页
            var isOpen;
            jquery(ELEM_TAB + ">.layui-tab-title>li").each(function () {
                if (jquery(this).attr("lay-id") === routerPath) {
                    isOpen = true
                }
            });

            if (!isOpen) { // 如果没有打开
                if (index.mTabList.length + 1 >= setter.maxTabNum) {
                    layer.msg("最多打开" + setter.maxTabNum + "个选项卡", {icon: 2, anim: 6});
                    return history.back()
                }
                o = true; // TODO 不知道干啥的
                element.tabAdd(ELEM_PAGETABS, { // 新增面板
                    id: routerPath,
                    title: '<span class="title">' + (router.name || "") + "</span>",
                    content: '<div lay-id="' + routerPath + '" lay-url="' + router.href + '"></div>'
                });
                if (routerPath !== layRouter.index) {
                    index.mTabList.push(router)
                }
                if (setter.cacheTab) { // 保存打开的面板，以便下次恢复
                    admin.putTempData("indexTabs", index.mTabList)
                }
            }

            t = ELEM_TAB + '>.layui-tab-content>.layui-tab-item>div[lay-id="' + routerPath + '"]';
            var layUrl = jquery(t).attr("lay-url");
            if (router.href !== layUrl) {
                // 触发admin模块的destroy(路由路径)事件
                layui.event.call(this, "admin", "destroy(" + routerPath + ")");
                jquery(t).attr("lay-url", router.href);
                isOpen = false;
                for (var i = 0; i < index.mTabList.length; i++) {
                    if (index.mTabList[i].href === layUrl) {
                        index.mTabList[i] = router
                    }
                }
                if (setter.cacheTab) {
                    admin.putTempData("indexTabs", index.mTabList)
                }
            }
            if (!isOpen || router.refresh) {
                if (router.refresh) { // 如果刷新，则销毁当前面板
                    // 触发admin模块的destroy(路由路径)事件
                    layui.event.call(this, "admin", "destroy(" + routerPath + ")")
                }
                index.renderView(router, t) // 重新渲染视图
            }
            if (!router.noChange && !router.refresh) {
                element.tabChange(ELEM_PAGETABS, routerPath)
            }
        } else {
            admin.activeNav(router.href);
            if (jquery(t).length === 0) {
                jquery(ELEM_BODY).html([
                    '<div class="layui-body-header">',
                    '   <span class="layui-body-header-title"></span>',
                    '   <span class="layui-breadcrumb pull-right" lay-filter="admin-body-breadcrumb" style="visibility: visible;"></span>',
                    "</div>",
                    '<div lay-id="' + routerPath + '" lay-url="' + router.href + '"></div>'
                ].join(""))
            } else {
                // 触发admin模块的destroy(路由路径)事件
                layui.event.call(this, "admin", "destroy(" + jquery(t).attr("lay-id") + ")");
                jquery(t).attr("lay-id", routerPath).attr("lay-url", router.href)
            }
            jquery('[lay-filter="admin-body-breadcrumb"]').html(index.getBreadcrumbHtml(routerPath));
            index.mTabList.splice(0, index.mTabList.length);
            if (routerPath === layRouter.index) {
                index.setTabTitle(jquery(router.name).text() || jquery(ELEM_SCROLL + ' [href="#/' + layRouter.index + '"]').text() || "主页")
            } else {
                index.mTabList.push(router);
                index.setTabTitle(router.name)
            }
            index.renderView(router, t);
            if (setter.cacheTab) {
                admin.putTempData("indexTabs", index.mTabList)
            }
        }
        if (admin.getPageWidth() <= 768) {
            admin.flexible(true)
        }
        jquery(".layui-table-tips-c").trigger("click")
    };

    index.renderView = function (router, selector, elem) {
        var $dom = jquery(selector);
        if (!elem) {
            elem = $dom.parent()
        }
        if (!router.iframe) {
            admin.showLoading({elem: elem, size: ""});
            admin.ajax({
                url: setter.viewPath + "/" + router.path.join("/") + setter.viewSuffix,
                data: router.search,
                dataType: "html",
                success: function (res) {
                    admin.removeLoading(elem);
                    if (typeof res !== "string") {
                        res = JSON.stringify(res)
                    }
                    if (res.indexOf("<tpl") === 0) { // 开启模板渲染
                        var tpl = jquery("<div>" + res + "</div>"), noTpl = {};
                        tpl.find("script,[tpl-ignore]").each(function (index) { // 获取不需要渲染的 script 标签
                            var $this = jquery(this);
                            noTpl["temp_" + index] = $this[0].outerHTML;
                            $this.after("${temp_" + index + "}").remove() // 插入标记符并移除这个标签
                        });
                        /**
                         模板中d表示的是router(当前路由信息)，如 #/system/user/id=1/sex=男
                         {
                            path: ["system", "user"], // 路径数组
                            search: {id: 1, sex: "男"}, // 参数列表
                            href: "/system/user/id=1/sex=男",
                            refresh: false // 如果是刷新触发的,值为true
                        }
                         模板中还可以使用layui变量
                         */
                        res = admin.util.tpl(tpl.html(), router, setter.tplOpen, setter.tplClose);
                        for (var key in noTpl) { // 渲染完成后恢复非模板的部分
                            res = res.replace("${" + key + "}", noTpl[key])
                        }
                    }
                    $dom.html(res); // 插入文档中
                    admin.renderPerm(); // 然后判断当前用户是否具有标签对应的权限，有:则显示，无:则删除
                    admin.renderTpl(selector + " [ew-tpl]"); // 动态模板渲染
                }
            })
        } else {
            $dom.html([
                '<div class="admin-iframe" style="-webkit-overflow-scrolling: touch;">',
                '   <iframe src="',
                router.iframe,
                '" class="admin-iframe" frameborder="0"></iframe>',
                "</div>"
            ].join(""));
        }
    };

    /**
     * 加载默认主页
     * @param menuItem
    {
        "url": "", // 路由url
        "name": "", // 菜单名称
        "iframe": "", // 使用iframe打开
        "loadSetting": true, // 是否恢复记忆的Tab
    }
     */
    index.loadHome = function (menuItem) {
        var indexTabs = admin.getTempData("indexTabs"); // 上次的打开的tab
        index.regRouter([menuItem]); // 注册路由
        if (setter.pageTabs) { // 是否开启多标签
            var router = layRouter.routerInfo(menuItem.url); // 获取路由对象
            layRouter.index = index.getHashPath(router); // 获取路由路径
            index.changeView(jquery.extend(router, {name: menuItem.name, iframe: menuItem.iframe, noChange: true}));
            // loadSetting 是否恢复记忆的Tab，默认为true；
            if (menuItem.loadSetting !== false && setter.cacheTab && indexTabs) {
                for (var i = 0; i < indexTabs.length; i++) {
                    index.changeView(jquery.extend(indexTabs[i], {noChange: true}))
                }
            }
        }
        admin.removeLoading(undefined, false);
        layRouter.init({index: menuItem.url, notFound: setter.routerNotFound}) // 路由没有找到的提示
    };

    /**
     * 打开一个新的选项卡
     * @param config
    {
        "url": "", // 路由url
        "name": "", // 菜单名称
        "iframe": "", // 使用iframe打开
    }
     */
    index.openNewTab = function (config) {
        index.regRouter([config]); // 临时注册路由，刷新页面就会消失
        layRouter.go(config.url) // 跳转到指定页面
    };

    /**
     * 关闭指定选项卡
     * @param url
     */
    index.closeTab = function (url) {
        element.tabDelete(ELEM_PAGETABS, index.getHashPath(url))
    };

    /**
     * 获取路由路径，如 system/user 不包含#也不包含参数等
     * @param url
     * @returns {*}
     */
    index.getHashPath = function (url) {
        if (!url || typeof url === "string") {
            url = layRouter.routerInfo(url)
        }
        return url.path.join("/")
    };

    index.go = function (url) {
        layRouter.go(url)
    };

    /**
     * 清除Tab记忆
     * Tab记忆功能是刷新页面的时候可以恢复上次打开的所有Tab，此方法用于清除已经缓存的Tab。
     * 在实际项目中，登录成功后应该调用此方法清除Tab记忆
     */
    index.clearTabCache = function () {
        admin.putTempData("indexTabs", null)
    };

    /**
     * 修改Tab标题
     * @param title
     * @param tabId 修改指定Tab标题文字
     */
    index.setTabTitle = function (title, tabId) {
        if (setter.pageTabs) { // 如果开启多标签
            if (!tabId) {
                tabId = index.getHashPath()
            }
            if (tabId) {
                jquery(ELEM_TAB + '>.layui-tab-title>li[lay-id="' + tabId + '"] .title').html(title || "")
            }
        } else {
            if (title) {
                jquery(ELEM_BODY_HEADER + ">.layui-body-header-title").html(title);
                jquery(ELEM_BODY_HEADER).addClass("show");
                jquery(ELEM_HEADER).css("box-shadow", "0 1px 0 0 rgba(0, 0, 0, .03)")
            } else {
                jquery(ELEM_BODY_HEADER).removeClass("show");
                jquery(ELEM_HEADER).css("box-shadow", "")
            }
        }
    };

    /**
     * 修改整个标题栏的html，只在单标签模式有效
     * @param html 标题的html
     * @returns {*}
     */
    index.setTabTitleHtml = function (html) {
        if (setter.pageTabs) {
            return
        }
        if (!html) {
            return jquery(ELEM_BODY_HEADER).removeClass("show")
        }
        jquery(ELEM_BODY_HEADER).html(html);
        jquery(ELEM_BODY_HEADER).addClass("show")
    };

    /**
     * 根据路由路径获取面包屑
     * @param routerPath 路由路径
     * @returns {*[]} 面包屑路径数组
     */
    index.getBreadcrumb = function (routerPath) {
        if (!routerPath) {
            routerPath = jquery(ELEM_BODY + ">div[lay-id]").attr("lay-id")
        }
        var breadcrumb = [];
        var $menu = jquery(ELEM_SCROLL).find('[href="#/' + routerPath + '"]'); // 通过url路径找到菜单
        if ($menu.length > 0) {
            breadcrumb.push($menu.text().replace(/(^\s*)|(\s*$)/g, ""))
        }
        while (true) {
            $menu = $menu.parent("dd").parent("dl").prev("a");
            if ($menu.length === 0) {
                break
            }
            breadcrumb.unshift($menu.text().replace(/(^\s*)|(\s*$)/g, ""))
        }
        return breadcrumb
    };

    /**
     * 获取面包屑的Html
     * @param routerPath
     * @returns {string|string}
     */
    index.getBreadcrumbHtml = function (routerPath) {
        var breadcrumb = index.getBreadcrumb(routerPath);
        var html = routerPath === layRouter.index ? "" : ('<a href="#/' + layRouter.index + '">首页</a>');
        for (var i = 0; i < breadcrumb.length - 1; i++) {
            if (html) {
                html += '<span lay-separator="">/</span>'
            }
            html += ("<a><cite>" + breadcrumb[i] + "</cite></a>")
        }
        return html
    };

    /**
     * 渲染菜单列表
     * @param menus 菜单数据
     * @param tpl html模板
     * @param callback html渲染完的自定义处理
         function(html, obj){
            // html 是渲染后的内容
            // obj.data 可获取处理后的数据，比如移除了show: false的数据
            // obj.side 是侧边栏的dom，例如$(obj.side + '>.layui-nav').html(html)
            // obj.render() 可更新nav的渲染
        }
     * @param tplOpen 模板变量开始标记
     * @param tplClose 模板变量结束标记
     * @param format 格式菜单数据的函数
     * @returns {boolean|*}
     */
    index.renderSide = function (menus, tpl, callback, tplOpen, tplClose, format) {

        if (typeof tpl === "function") {
            tplClose = tplOpen;
            tplOpen = callback;
            callback = tpl;
            tpl = undefined
        }

        if ("Array" !== admin.util.isClass(menus)) {
            tpl = menus.tpl;
            callback = menus.callback;
            tplOpen = menus.tplOpen;
            tplClose = menus.tplClose;
            format = menus.format;
            menus = menus.data
        }

        function formatMenu(menus) {
            for (var i = menus.length - 1; i >= 0; i--) {
                if (format) { // 格式化菜单项
                    menus[i] = format(menus[i])
                }
                if (menus[i].subMenus) { // 递归调用
                    formatMenu(menus[i].subMenus)
                }
                if (menus[i].show === false) { // 如果菜单项不显示，则删除它
                    menus.splice(i, 1)
                } else {
                    if (!menus[i].target) { // 在哪里打开该url
                        menus[i].target = "_self"
                    }
                    if (!menus[i].url) { //
                        menus[i].url = "javascript:;"
                    }
                }
            }
        }

        formatMenu(menus);
        var menuHtml = admin.util.tpl(tpl || jquery("#sideNav").html() || "", menus, tplOpen || setter.tplOpen, tplClose || setter.tplClose);
        if (callback) {
            return callback(menuHtml, {
                data: menus, side: ELEM_SCROLL, render: function () {
                    element.render("nav", "admin-side-nav")
                }
            })
        }
        jquery(ELEM_SCROLL + ">.layui-nav").html(menuHtml);
        element.render("nav", "admin-side-nav")
    };

    var h = ".layui-layout-admin .site-mobile-shade";
    if (jquery(h).length === 0) {
        jquery(".layui-layout-admin").append('<div class="site-mobile-shade"></div>')
    }

    jquery(h).click(function () {
        admin.flexible(true)
    });

    if (setter.pageTabs && jquery(ELEM_TAB).length === 0) {
        jquery(ELEM_BODY).html([
            '<div class="layui-tab" lay-allowClose="true" lay-filter="',
            ELEM_PAGETABS,
            '" lay-autoRefresh="',
            setter.tabAutoRefresh == true,
            '">',
            '   <ul class="layui-tab-title"></ul><div class="layui-tab-content"></div>',
            "</div>",
            '<div class="layui-icon admin-tabs-control layui-icon-prev" ew-event="leftPage"></div>',
            '<div class="layui-icon admin-tabs-control layui-icon-next" ew-event="rightPage"></div>',
            '<div class="layui-icon admin-tabs-control layui-icon-down">',
            '   <ul class="layui-nav" lay-filter="admin-pagetabs-nav">',
            '      <li class="layui-nav-item" lay-unselect>',
            '         <dl class="layui-nav-child layui-anim-fadein">',
            '            <dd ew-event="closeThisTabs" lay-unselect><a>关闭当前标签页</a></dd>',
            '            <dd ew-event="closeOtherTabs" lay-unselect><a>关闭其它标签页</a></dd>',
            '            <dd ew-event="closeAllTabs" lay-unselect><a>关闭全部标签页</a></dd>',
            "         </dl>",
            "      </li>",
            "   </ul>",
            "</div>"
        ].join(""));
        element.render("nav", "admin-pagetabs-nav")
    }

    element.on("nav(" + ELEM_NAV + ")", function (s) {
        var r = jquery(s).attr("href");
        if (r.indexOf("#") !== 0 || jquery(ELEM_TAB).attr("lay-autoRefresh") != "true") {
            return
        }
        if (!o) {
            admin.refresh(r.substring(1), true)
        }
    });

    element.on("tab(" + ELEM_PAGETABS + ")", function () {
        var url = jquery(this).attr("lay-id");
        var r = jquery(ELEM_TAB + '>.layui-tab-content>.layui-tab-item>div[lay-id="' + url + '"]').attr("lay-url");
        admin.activeNav(r);
        admin.rollPage("auto");
        if (jquery(ELEM_TAB).attr("lay-autoRefresh") == "true" && !o) {
            admin.refresh(r, true)
        } else {
            layRouter.go(r)
        }
        o = false;
        admin.resizeTable(0);
        // 触发admin模块的show(路由路径)事件
        layui.event.call(this, "admin", "show(" + url + ")");
        // 触发admin模块的tab({*})事件
        layui.event.call(this, "admin", "tab({*})", {layId: url})
    });

    element.on("tabDelete(" + ELEM_PAGETABS + ")", function (s) {
        if (s.index > 0 && s.index <= index.mTabList.length) {
            var url = index.getHashPath(index.mTabList[s.index - 1].href);
            // 触发admin模块的destroy(路由路径)事件
            layui.event.call(this, "admin", "destroy(" + url + ")");
            index.mTabList.splice(s.index - 1, 1);
            if (setter.cacheTab) {
                admin.putTempData("indexTabs", index.mTabList)
            }
            // 触发admin模块的tabDelete({*})事件，即监听tab关闭事件
            layui.event.call(this, "admin", "tabDelete({*})", {layId: url})
        }
        if (jquery(ELEM_TAB + ">.layui-tab-title>li.layui-this").length === 0) {
            jquery(ELEM_TAB + ">.layui-tab-title>li:last").trigger("click")
        }
    });

    jquery(document).off("click.navMore").on("click.navMore", "[nav-bind]", function () {
        var r = jquery(this).attr("nav-bind");
        jquery('ul[lay-filter="' + ELEM_NAV + '"]').addClass("layui-hide");
        jquery('ul[nav-id="' + r + '"]').removeClass("layui-hide");
        jquery(ELEM_HEADER + ">.layui-nav .layui-nav-item").removeClass("layui-this");
        jquery(this).parent(".layui-nav-item").addClass("layui-this");
        if (admin.getPageWidth() <= 768) {
            admin.flexible(false)
        }
        // 监听多系统切换事件
        layui.event.call(this, "admin", "nav({*})", {navId: r})
    });

    if (setter.openTabCtxMenu && setter.pageTabs) {
        layui.use("contextMenu", function () {
            if (!layui.contextMenu) {
                return
            }
            jquery(ELEM_TAB + ">.layui-tab-title").off("contextmenu.tab").on("contextmenu.tab", "li", function (event) {
                var url = jquery(this).attr("lay-id");
                layui.contextMenu.show([
                    {
                        icon: "layui-icon layui-icon-refresh",
                        name: "刷新当前",
                        click: function () {
                            element.tabChange(ELEM_PAGETABS, url);
                            var t = jquery(ELEM_TAB + '>.layui-tab-content>.layui-tab-item>div[lay-id="' + url + '"]').attr("lay-url");
                            if ("true" != jquery(ELEM_TAB).attr("lay-autoRefresh")) {
                                admin.refresh(t)
                            }
                        }
                    },
                    {
                        icon: "layui-icon layui-icon-close-fill ctx-ic-lg",
                        name: "关闭当前",
                        click: function () {
                            admin.closeThisTabs(url);
                        }
                    },
                    {
                        icon: "layui-icon layui-icon-unlink",
                        name: "关闭其他",
                        click: function () {
                            admin.closeOtherTabs(url)
                        }
                    },
                    {
                        icon: "layui-icon layui-icon-close ctx-ic-lg",
                        name: "关闭全部",
                        click: function () {
                            admin.closeAllTabs()
                        }
                    }
                ], event.clientX, event.clientY);
                return false
            })
        })
    }

    exports("index", index)
});